package com.pandas.community.controller;

import com.pandas.community.Utils.CommunityConstant;
import com.pandas.community.Utils.CommunityUtil;
import com.pandas.community.Utils.HostHolder;
import com.pandas.community.annotation.LoginRequired;
import com.pandas.community.entity.User;
import com.pandas.community.service.FollowService;
import com.pandas.community.service.LikeService;
import com.pandas.community.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant{
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Value("${community.path.domain}")
    private String domain;

    @Value(("${server.servlet.context-path}"))
    private String contextPath;

    @Value("${community.path.upload}")
    private String uploadPath;

    //获取账号设置页面
    @LoginRequired
    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }


    //上传头像
    @LoginRequired
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model){
        if(headerImage == null){
            model.addAttribute("picError","请选择一张图片");
            return "/site/setting";
        }

        //获得文件名， 重新命名
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        boolean isValid = suffix.equals(".png") || suffix.equals(".jpg") || suffix.equals(".jpeg");

        if(StringUtils.isBlank(suffix) || !isValid ){
            model.addAttribute("picError","文件的格式不正确");
            return "/site/setting";
        }

        //重命名存入服务器
        filename = CommunityUtil.generateUUID() + suffix;
        File savePath = new File(uploadPath + "/" + filename);
        try {
            headerImage.transferTo(savePath);
        } catch (IOException e){
            logger.error("上传头像图片失败" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务期发生异常", e);
        }

        // 更新当前用户头像访问路径
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        userService.updateHeadUrl(user.getId(), headerUrl);
        return "redirect:/index";
    }

    // 获取头像
    @RequestMapping(value = "/header/{filename}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response){
        //服务器存储路径
        filename = uploadPath + "/" + filename;
        //文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //相应图片
        response.setContentType("image/" + suffix);
        //放在括号内会自动关闭
        try(
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(filename)
        ){
            byte[] buffer = new byte[1024];
            int b = 0;
            while((b = fis.read(buffer)) != -1){
                os.write(buffer, 0, b);
            }
        }catch (IOException e){
            logger.error("读取头像失败：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/profile/{userid}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userid") int userid, Model model){
        User user = userService.selectById(userid);
        if(user == null) throw  new IllegalArgumentException();
        //用户
        model.addAttribute("user", user);

        // 点赞数量
        int userLikeCount = likeService.getUserLikeStatus(user.getId());
        model.addAttribute("likeCount", userLikeCount);

        //关注数量
        long followeeCount = followService.getFolloweeCount(userid, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);

        //跟随者数量
        long followerCount = followService.getFollowerCount(ENTITY_TYPE_USER, userid);
        model.addAttribute("followerCount", followerCount);

        //是否已关注
        boolean hasFollowed = false;
        if(hostHolder.getUser() != null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userid);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }
}
